<?php
namespace Seller\Logic;
use Think\Model\RelationModel;

class OrderLogic extends RelationModel
{
    /**
     * @param array $condition  搜索条件
     * @param string $order   排序方式 
     * @param int $start    limit开始行
     * @param int $page_size  获取数量
     */
    public function getOrderList($condition,$order='',$start=0,$page_size=20){
        $res = M('order a')
        ->field("a.*,c.company,c.company_address,c.mobile,c.fast_flag,d.fast_flag as shop_fast_flag,c.slow_flag,d.slow_flag as shop_slow_flag,CONCAT(biaoshi_xian,if(c.fast_flag='1','快','')) as biaoshi_xian,c.rpay,c.rpay_store,d.mobile_staus")
        ->join('ty_order_goods b on a.order_id=b.order_id','LEFT')
		->join('ty_users c on a.user_id=c.user_id','LEFT')
        ->join('ty_store d on a.store_id=d.store_id','LEFT')
        ->group('a.order_id')
		->where($condition)->limit("$start,$page_size")->order($order.',c.user_id asc')->select();
        return $res;
    }
    /*
     * 获取订单商品详情
     */
  public function getOrderGoods($order_id){
         $sql = "SELECT g.last_name,p.sku,p.spu,g.goods_name,g.original_img,g.fenbu_koudian,o.*,TRUNCATE(o.goods_num * o.member_goods_price,3) AS goods_total,TRUNCATE(o.goods_num * TRUNCATE (( o.member_goods_price - 0),3),3) AS goods_kou_total,TRUNCATE(o.member_goods_price - 0,3) AS goods_kou_price FROM __PREFIX__order_goods o ".
            "LEFT JOIN __PREFIX__goods g ON o.goods_id = g.goods_id LEFT JOIN __PREFIX__spec_goods_price p ON p.key = o.spec_key LEFT JOIN __PREFIX__spec_goods_price sc ON sc.goods_id = o.goods_id WHERE o.order_id = $order_id and o.store_id=".STORE_ID.' group by o.rec_id';
        $res = $this->query($sql);
        foreach ($res as $key =>$vs){
            $goods_kou_total = sanwei($vs['goods_num'] * ($vs['member_goods_price'] - 0));
            $res[$key]['goods_kou_total']=$goods_kou_total;
            // $sku = M('spec_goods_price')->where(['key'=>$vs['spec_key']])->getField('sku');
            // $res[$key]['sku'] = $sku;
            if(!empty($vs['last_name'])){
                $res[$key]['goods_name'] = $vs['last_name'];
            }
        }
        return $res;
    }

    /*
     * 获取订单信息
     */
    public function getOrderInfo($order_id,$store_id=0)
    {
         if($store_id != 0){
            $store_id = $store_id;
        }else{
            $store_id = STORE_ID;
        }
        //  订单总金额查询语句		
        $order = M('order a')
		->field('a.*,b.mobile,b.company,b.rpay,b.rpay_store')
		->join('ty_users b on a.user_id=b.user_id','LEFT')
		->where("order_id = $order_id and a.store_id=".$store_id)->find();
		
		if($order){
			$order['address2'] = $this->getAddressName($order['province'],$order['city'],$order['district']);
			$order['address2'] = $order['address2'].$order['address'];
		}
        return $order;
    }

    /*
     * 根据商品型号获取商品
     */
    public function get_spec_goods($goods_id_arr){
    	if(!is_array($goods_id_arr)) return false;
    		foreach($goods_id_arr as $key => $val)
    		{
    			$arr = array();
    			$goods = M('goods')->where("goods_id = $key")->find();
    		
    			$arr['goods_id'] = $key; // 商品id
    			$arr['goods_name'] = $goods['goods_name'];
    			$arr['goods_sn'] = $goods['goods_sn'];
    			$arr['market_price'] = $goods['market_price'];
    			$arr['goods_price'] = $goods['shop_price'];
    			$arr['cost_price'] = $goods['cost_price'];
    			$arr['member_goods_price'] = $goods['shop_price'];
				$arr['points'] = $goods['points'];
				$arr['floating'] = $goods['floating'];
				$arr['prom_type'] = $goods['prom_type'];
				$arr['prom_id'] = $goods['prom_id'];
				$arr['is_yanzhi'] = $goods['is_yanzhi'];
				$arr['rank_status'] = $goods['p_status'];
				$arr['stop_yijia'] = $goods['stop_yijia'];
				$arr['fenbu_koudian'] = $goods['fenbu_koudian'];
					foreach($val as $k => $v)
					{
						$arr['goods_num'] = $v['goods_num']; // 购买数量
						// 如果这商品有规格
						if($k != 'key')
						{
							$arr['spec_key'] = $k;
							$arr['goods_id'] = $key;
							$new_price=get_goods_huodong($key,$k);
							$arr['spec_key_name'] = $new_price['key_name'];
							$arr['prom_msg'] = $new_price['prom_msg'];
							$arr['member_goods_price'] = $arr['goods_price'] =\sanwei($new_price['price']);
							$arr['sku'] = $new_price['sku'];
						}
						$order_goods[] = $arr;
					}
				
    		}
    		return $order_goods;
    }

    /*
     * 订单操作记录
     */
    public function orderActionLog($order,$action,$note='',$action_user = 0,$user_type = 0){
        $data['order_id'] = $order['order_id'];
        $data['action_user'] = $action_user;
        $data['store_id'] = STORE_ID; 
        $data['user_type'] = $user_type; // 0管理员 1商家 2前台用户
        $data['action_note'] = $note;
        $data['order_status'] = $order['order_status'];
        $data['pay_status'] = $order['pay_status'];
        $data['shipping_status'] = $order['shipping_status'];
        $data['log_time'] = time();
        $data['status_desc'] = $action;
        if(!empty(session('admin_id'))){
            $data['admin_id'] = session('admin_id');
        }
        return M('order_action')->add($data);//订单操作记录
    }

    /*
     * 获取订单商品总价格
     */
    public function getGoodsAmount($order_id){
        $sql = "SELECT SUM(goods_num * goods_price) AS goods_amount FROM __PREFIX__order_goods WHERE order_id = {$order_id}";
        $res = $this->query($sql);
        return $res[0]['goods_amount'];
    }

    /**
     * 得到发货单流水号
     */
    public function get_delivery_sn()
    {
        /* 选择一个随机的方案 */send_http_status('310');
		mt_srand((double) microtime() * 1000000);
        return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /*
     * 获取当前可操作的按钮
     */
    public function getOrderButton($order){
        /*
         *  操作按钮汇总 ：付款、设为未付款、确认、取消确认、无效、去发货、确认收货、申请退货
         * 
         */
    	$os = $order['order_status'];//订单状态
    	$ss = $order['shipping_status'];//发货状态
    	$ps = $order['pay_status'];//支付状态
        $btn = array();
        if($order['pay_code'] == 'cod') {
        	if($os == 0 && $ss == 0){
        		$btn['confirm'] = '确认';
        	}elseif($os == 1 && $ss == 0 ){
        		$btn['delivery'] = '去发货';
        		$btn['cancel'] = '取消确认';
        	}elseif($ss == 1 && $os == 1 && $ps == 0){
        		$btn['pay'] = '付款';
        	}elseif($ps == 1 && $ss == 1 && $os == 1){
        		//$btn['pay_cancel'] = '设为未付款';
        	}
        }else{
        	if($ps == 0 && $os == 0){
        		$btn['pay'] = '付款';
        	}elseif($os == 0 && $ps == 1){
        		//$btn['pay_cancel'] = '设为未付款';
        		$btn['confirm'] = '确认';
        	}elseif($os == 1 && $ps == 1 && $ss==0){
        		$btn['cancel'] = '取消确认';
        		$btn['delivery'] = '去发货';
        	}
        } 
               
        if($ss == 1 && $os == 1 && $ps == 1){
        	$btn['delivery_confirm'] = '确认收货';
        	$btn['refund'] = '申请退货';
        }elseif($os == 2 || $os == 4){
        	$btn['refund'] = '申请退货';
        }elseif($os == 3 || $os == 5){
        	$btn['remove'] = '移除';
        }
        if($os != 5){
        	$btn['invalid'] = '无效';
        }
        return $btn;
    }

    
    /*
* 获取当前可操作的按钮
*/
    public function getOrderButtons($order,$count=0){
        /*
         *  操作按钮汇总 ：付款、设为未付款、确认、取消确认、无效、去发货、确认收货、申请退货
         *
         */
        $os = $order['order_status'];//订单状态
        $ss = $order['shipping_status'];//发货状态
        $ps = $order['pay_status'];//支付状态
        $btn = array();
        $btn['ModifyOrder'] = 0;//修改订单
        $btn['SplitOrders'] = 0;//拆分订单
        $btn['PrintOrder'] = 0;//打印订单
//        if($order['pay_code'] == 'cod') {
            if($os == 0 && $ss == 0){
                $btn['ModifyOrder'] = 1;//修改订单
                $btn['SplitOrders'] = 1;//拆分订单
                $btn['PrintOrder'] = 1;//打印订单
            }elseif($os == 1 && $ss == 0 ){//未发货
                $btn['ModifyOrder'] = 1;//修改订单
                $btn['SplitOrders'] = 1;//拆分订单
                $btn['PrintOrder'] = 1;//打印订单
//                $btn['cancel'] = '取消确认';
            }elseif($ss == 1 && $os == 1 && $ps == 0){//已发货
                $btn['PrintOrder'] = 1;//打印订单
            }elseif($ps == 1 && $ss == 1 && $os == 1){
                $btn['PrintOrder'] = 1;//打印订单
                //$btn['pay_cancel'] = '设为未付款';
            }
//        }
        if($count<=0){
            $btn['SplitOrders'] = 0;//拆分订单
        }
        
//        else{
//            if($ps == 0 && $os == 0){
//                $btn['pay'] = '付款';
//            }elseif($os == 0 && $ps == 1){
//                //$btn['pay_cancel'] = '设为未付款';
//                $btn['confirm'] = '确认';
//            }elseif($os == 1 && $ps == 1 && $ss==0){
//                $btn['cancel'] = '取消确认';
//                $btn['delivery'] = '去发货';
//            }
//        }
//
//        if($ss == 1 && $os == 1 && $ps == 1){
//            $btn['delivery_confirm'] = '确认收货';
//            $btn['refund'] = '申请退货';
//        }elseif($os == 2 || $os == 4){
//            $btn['refund'] = '申请退货';
//        }elseif($os == 3 || $os == 5){
//            $btn['remove'] = '移除';
//        }
//        if($os != 5){
//            $btn['invalid'] = '无效';
//        }
        return $btn;
    }
    public function orderProcessHandle($order_id,$act,$store_id = 0){
    	$updata = array();
    	switch ($act){
    		case 'pay': //付款
                $order_sn = M('order')->where("order_id = $order_id")->getField("order_sn");
                update_pay_status($order_sn); // 调用确认收货按钮
    			return true;    			
    		case 'pay_cancel': //取消付款
    			$updata['pay_status'] = 0;
    			break;
    		case 'confirm': //确认订单
    			$updata['order_status'] = 1;
    			break;
    		case 'cancel': //取消确认
    			$updata['order_status'] = 0;
    			break;
    		case 'invalid': //作废订单
    			$updata['order_status'] = 5;
    			break;
    		case 'remove': //移除订单
    			$this->delOrder($order_id);
    			break;
    		case 'delivery_confirm'://确认收货
    			confirm_order($order_id); // 调用确认收货按钮
    			return true;
    		default:
    			return true;
    	}
    	$order = M('order')->where(['order_id'=>$order_id])->find();
    	if($updata['order_status'] == 5){
            if($order['coupon_price'] > 0){
                return false;
            }
        }
        $seller_id = session('seller_id');
        M('order')->where("order_id = $order_id and store_id = $store_id")->save($updata);
        if($updata['order_status'] == 5){
            M('users_price')->where('order_id='.$order_id)->setField(['price'=>0]);
        }
        $order = M('order')->where(['order_id'=>$order_id])->find();
        $super = session('super');
        if( $super == 'shadow'){
            $seller_id = 0;
            $user_type = 0;
            $msg = '管理员id:'.session('admin_id').'作废订单';
        }else{
            $user_type = 1;
            $msg = '商家：作废订单';
        }
        $this->orderActionLog($order,'edit',$msg,$seller_id,$user_type);//操作日志
    	return $order_id;//改变订单状态
    }
    
    /**
     *	处理发货单
     * @param array $data  查询数量
     */
    public function deliveryHandle($data,$store_id){
		$order = $this->getOrderInfo($data['order_id']);
		$orderGoods = $this->getOrderGoods($data['order_id']);
		$selectgoods = $data['goods'];
		$data['order_sn'] = $order['order_sn'];
		$data['delivery_sn'] = $this->get_delivery_sn();
		$data['zipcode'] = $order['zipcode'];
		$data['user_id'] = $order['user_id'];
		$data['admin_id'] = session('seller_id');
		$data['consignee'] = $order['consignee'];
		$data['mobile'] = $order['mobile'];
		$data['country'] = $order['country'];
		$data['province'] = $order['province'];
		$data['city'] = $order['city'];
		$data['district'] = $order['district'];
		$data['address'] = $order['address'];
		$data['shipping_code'] = $order['shipping_code'];
		$data['shipping_name'] = $order['shipping_name'];
		$data['shipping_price'] = $order['shipping_price'];
		$data['create_time'] = time();
        $data['store_id'] = $store_id;
		$did = M('delivery_doc')->add($data);

		$is_delivery = 0;
		foreach ($orderGoods as $k=>$v){
			if($v['is_send'] == 1){
				$is_delivery++;
			}			
			if($v['is_send'] == 0 && in_array($v['rec_id'],$selectgoods)){
				$res['is_send'] = 1;
				$res['delivery_id'] = $did;
                M('order_goods')->where("rec_id={$v['rec_id']}  and store_id = $store_id")->save($res);//改变订单商品发货状态
				$is_delivery++;
			}
		}
		$updata['shipping_time'] = time();
		if($is_delivery == count($orderGoods)){
			$updata['shipping_status'] = 1;
		}else{
			$updata['shipping_status'] = 2;
		}
                
        M('order')->where("order_id ={$data['order_id']} and store_id = $store_id")->save($updata);//改变订单状态
	    $seller_id = session('seller_id');
		return $this->orderActionLog($order,'订单发货',$data['note'],$seller_id,1);//操作日志
    }

    /**
     * 获取地区名字
     * @param int $p
     * @param int $c
     * @param int $d
     * @return string
     */
    public function getAddressName($p=0,$c=0,$d=0){
        $p = M('region')->where(array('id'=>$p))->field('name')->find();
        $c = M('region')->where(array('id'=>$c))->field('name')->find();
        $d = M('region')->where(array('id'=>$d))->field('name')->find();
        return $p['name'].','.$c['name'].','.$d['name'].',';
    }

    /**
     * 删除订单
     *
     */
    function delOrder($order_id,$store_id){
    	$a = M('order')->where(array('order_id'=>$order_id,'store_id'=>$store_id))->delete();
    	$b = M('order_goods')->where(array('order_id'=>$order_id,'store_id'=>$store_id))->delete();
    	return $a && $b;
    }

}